package Java7_Concurrency_Cookbook.concurrency_test.phaser_test;

import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

/**
 * @author lixiangke
 * @date 2017/12/4
 */
public class Task implements Runnable {
    private int time;
    private Phaser phaser;

    public Task(int time, Phaser phaser) {
        this.time = time;
        this.phaser = phaser;
    }

    @Override
    public void run() {
        phaser.arrive();

        String tName = Thread.currentThread().getName();
        System.out.printf("%s: Entering phase 1.\n", tName);
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("%s: Finishing phase 1.\n", tName);
        phaser.arriveAndAwaitAdvance();

        System.out.printf("%s: Entering phase 2.\n", tName);
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("%s: Finishing phase 2.\n", tName);
        phaser.arriveAndAwaitAdvance();

        System.out.printf("%s: Entering phase 3.\n", tName);
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.printf("%s: Finishing phase 3.\n", tName);
        phaser.arriveAndDeregister();
    }
}
